<template>
  <div class="tool-container">
    <h1 class="main-title">开发工具下载中心</h1>

    <div class="search-container">
      <el-input v-model="searchQuery" placeholder="搜索开发工具..." class="search-input" :prefix-icon="Search" clearable />
    </div>

    <el-tabs v-model="activeCategory" class="tool-tabs" @tab-change="handleTabChange" v-show="showTabs">
      <el-tab-pane v-for="category in categories" :key="category.id" :label="category.name" :name="category.id">
      </el-tab-pane>
    </el-tabs>

    <el-row :gutter="24" v-loading="loading">
      <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="tool in filteredTools" :key="tool.name" class="tool-col">
        <el-card class="tool-card" shadow="hover">
          <div class="tool-content">
            <div class="tool-header">
              <img :src="tool.img || '/images/default-tool.png'" class="tool-image" />
              <h4 class="tool-title">{{ tool.name }}</h4>
            </div>
            <p class="tool-desc" :title="tool.description">{{ tool.description }}</p>
            <div class="tool-footer">
              <span class="download-count">
                <el-icon>
                  <download />
                </el-icon>
                {{ tool.downloadCount }}次下载
              </span>
              <el-button type="primary" size="small" class="download-btn" @click="handleDownload(tool)" :loading="downloadLoading[tool.id]">
                下载
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { Search, Download } from '@element-plus/icons-vue'
import { getToolCategoryList } from '../api/toolCategory'
import { getToolsList, increaseDownloadCount } from '../api/tools'
import { downloadFile } from '../api/file'
import { ElMessage } from 'element-plus'
import { useTokenStore } from '../stores/index'
const tokenStore = useTokenStore()

const showTabs = computed(() => !searchQuery.value)
const activeCategory = ref(1)
const categories = ref([])
const tools = ref([])
const searchQuery = ref('')
const loading = ref(false)
const allTools = ref([])
const downloadLoading = ref({})

onMounted(() => {
  loadCategories()
})

watch(searchQuery, debounce(() => {
  if (searchQuery.value) {
    tools.value = allTools.value.filter(tool => 
      tool.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      tool.description.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  } else {
    loadTools()
  }
}, 300))

function debounce(fn, delay) {
  let timer = null
  return function () {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, arguments)
    }, delay)
  }
}

const loadCategories = async () => {
  loading.value = true
  const param = {
    pageNum: 1,
    pageSize: 1000,
    isAll: true
  }
  try {
    const res = await getToolCategoryList(param)
    categories.value = res.data.records
    if (categories.value.length > 0) {
      activeCategory.value = categories.value[0].id
      loadTools()
    }
  } catch (error) {
    console.error('加载分类失败:', error)
  } finally {
    loading.value = false
  }
}

const loadTools = async () => {
  loading.value = true
  const params = {
    pageNum: 1,
    pageSize: 1000,
    keyword: searchQuery.value,
    toolCategoryId: searchQuery.value ? undefined : activeCategory.value
  }
  try {
    const res = await getToolsList(params)
    tools.value = res.data.records
    if (!searchQuery.value) {
      allTools.value = res.data.records
    }
  } catch (error) {
    console.error('加载工具失败:', error)
    ElMessage.error('加载工具失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleTabChange = (tabName) => {
  activeCategory.value = Number(tabName)
  loadTools()
}

const handleDownload = (tool) => {
  if (tokenStore.token == null || tokenStore.token == '') {
    ElMessage.error('请先登录')
    return
  }

  downloadLoading.value[tool.id] = true
  downloadFile(4, tool.fileName).then((res) => {
    const blob = new Blob([res])
    const downloadLink = document.createElement('a')
    const objectUrl = URL.createObjectURL(blob)

    downloadLink.href = objectUrl
    downloadLink.download = tool.fileName

    document.body.appendChild(downloadLink)
    downloadLink.click()

    document.body.removeChild(downloadLink)
    URL.revokeObjectURL(objectUrl)

    increaseDownloadCount(tool.id).then((res) => {
      ElMessage.success('下载成功')
      loadTools()
      downloadLoading.value[tool.id] = false
    }).catch((error) => {
      console.log(error)
      ElMessage.error('下载失败，请稍后重试')
      downloadLoading.value[tool.id] = false
    })
  }).catch(error => {
    console.log(error)
    ElMessage.error('下载失败，请稍后重试')
    downloadLoading.value[tool.id] = false
  })
}

const filteredTools = computed(() => {
  return tools.value
})
</script>

<style scoped>
.tool-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  min-height: 500px;
}

.main-title {
  text-align: center;
  color: #409EFF;
  font-size: 2.5rem;
  margin-bottom: 30px;
  font-weight: 600;
}

.search-container {
  max-width: 500px;
  margin: 0 auto 40px;
}

.search-input {
  width: 100%;
}

.tool-tabs {
  margin-top: 20px;
}

.tool-col {
  margin-bottom: 24px;
}

.tool-card {
  height: 240px;
  transition: all 0.3s;
  border-radius: 8px;
}

.tool-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.tool-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px;
}

.tool-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 12px;
}

.tool-image {
  width: 60px;
  height: 60px;
  object-fit: contain;
  margin-bottom: 12px;
  border-radius: 8px;
}

.tool-title {
  font-size: 16px;
  margin: 0;
  color: #303133;
  font-weight: 500;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}

.tool-desc {
  flex: 1;
  font-size: 14px;
  color: #606266;
  margin: 0;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.tool-footer {
  margin-top: 16px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.download-count {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 12px;
}

.download-btn {
  padding: 8px 16px;
  font-size: 13px;
  border-radius: 4px;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 5px;
}

:deep(.el-dropdown-menu__item .el-icon) {
  margin-right: 5px;
}
</style>